#!/bin/bash
#
# 'start' - Shell script to start ASSP
#

if [ -z "$1" ] ; then
  BASE=`echo $(dirname $(readlink -f $0))`
else
  BASE=$1;
fi
export BASE

PROXY_CFG=$BASE/assp.cfg
pidfile=${BASE}/pid

# Override pidfile if a name is given in assp.cfg
if [ -f ${PROXY_CFG} ] ; then
  pidfile="`grep "^pidfile.*=" ${PROXY_CFG} | sed -e 's/pidfile.*=//g'`"
fi

# If no PATH is given use $BASE as offset
echo "${pidfile}" | grep -q '/' || pidfile=${BASE}/${pidfile}

# create pidfile if assp.pl is already running in this directory according
to 'ps' and no pidfile exists
if [ ! -f ${pidfile} ] ; then
  PROGID="`ps -ef | grep "${BASE}/[a]ssp.pl" | awk '{print $2}'`"
  [ -z "${PROGID}" ] || echo -n "${PROGID}" >${pidfile}
fi

if [ -f ${pidfile} ] ; then
  # Sanitize content of pidfile
  PROGID=`cat ${pidfile} | tr -cd 0-9`
  if [ -z "${PROGID}" ] ; then
    echo "delete invalid pidfile" >&2
    rm -f ${pidfile}
  else
    if ps --pid ${PROGID} | tail -n+2 | grep -q "[a]ssp" ; then
      echo "ASSP already running (${PROGID})" >&2
      exit 1
    else
      now=`date +%s`
      pidtime=`stat -c%Z ${pidfile}`
      pidage=`echo $((${now} - ${pidtime}))`
      if [ ${pidage} -gt 90 ] ; then
        rm -f ${pidfile}
      else
        echo "strange pid in ${pidfile}, abort" >&2
        exit 1
      fi
    fi
  fi
fi

echo Starting ASSP Anti-SPAM Proxy server in ${BASE}
trap '' 1
LANG=
export LANG
exec ${BASE}/assp.pl ${BASE} &